package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        R<Employee> result = employeeService.login(employee);
        if (result.getCode() == 1) {
            session.setAttribute("employee", result.getData().getId());
        }
        return result;
    }

    @PostMapping("/logout")
    public R logout(HttpSession session) {
        session.invalidate();
        return R.success("退出登录成功");
    }

    @PostMapping
    public R save(@RequestBody Employee employee, HttpSession session) {
        Long empId = (Long) session.getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("添加成功");
    }
    @GetMapping("/page")
    public R page(@RequestParam(defaultValue = "1") Integer page,
                  @RequestParam(defaultValue = "10") Integer pageSize,
                  String name){
        Page<Employee> pageList = employeeService.findByPage(page, pageSize, name);
        return R.success(pageList);
    }

    @PutMapping
    public R update(@RequestBody Employee employee){
        employeeService.update(employee);
        return R.success("编辑成功");
    }

   @GetMapping("/{id}")
    public R detail(@PathVariable Integer id){
        Employee employee = employeeService.findById(id);
        return R.success(employee);
   }
}
